package com.x.ganjiang.gen.gen;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.x.ganjiang.gen.dao.FileInfoIService;
import com.x.ganjiang.gen.data.FileInfoDO;
import com.x.ganjiang.gen.infra.mapper.FileInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

//@Component
@Slf4j
public class FileRepositoryRunner implements ApplicationRunner {

    @Resource
    private FileInfoMapper fileInfoMapper;

    @Resource
    private FileInfoIService fileInfoIService;

    @Resource
    private ConfigurableApplicationContext ctx;

    public static final String fileDir = "E:\\FileRepository";


    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            excludeNonExistentInDBFiles();
            gen();
            // 删除到回收站
            delFileByDB();
        } catch (Exception e) {
            log.error("FileRepositoryRunner.run error", e);
        } finally {
            int code = SpringApplication.exit(ctx, () -> 0); // 0 表示正常退出
            System.exit(code);
        }
    }

    /**
     * 移出不存在数据库的文件
     */
    public void excludeNonExistentInDBFiles() {
        String dirPath = fileDir+ "\\fileTmp";
        File[] ls = FileUtil.ls(fileDir);
        for (File file : ls) {
            if (!file.isFile()) {
                continue;
            }
            String fileFullName = file.getName();
            Pair<String, String> nameAndType = getNameAndType(file);
            String fileName = nameAndType.getLeft();
            String fileType = nameAndType.getRight();
            LambdaQueryWrapper<FileInfoDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FileInfoDO::getFileName, fileName);
            queryWrapper.eq(FileInfoDO::getFileType, fileType);
            List<FileInfoDO> list = fileInfoIService.list(queryWrapper);
            if (list == null || list.isEmpty()) {
                FileUtil.move(file, new File(dirPath + "//" + fileFullName), false);
                log.info("移动文件：{}", fileFullName);
            }
        }
    }

    /**
     * 文件生成
     */
    public void gen() {
        String dirPath = fileDir+ "\\fileTmp";
        String firstCategory = "per";
        String secondCategory = "install_package";

        File[] ls = FileUtil.ls(dirPath);
        for (File file : ls) {
            if (file.isFile()) {
                String fileFullName = file.getName();
                Pair<String, String> nameAndType = getNameAndType(file);
                String fileName = nameAndType.getLeft();
                String fileType = nameAndType.getRight();
                LambdaQueryWrapper<FileInfoDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(FileInfoDO::getFileName, fileName);
                queryWrapper.eq(FileInfoDO::getFileType, fileType);
                queryWrapper.eq(FileInfoDO::getIsDel, "0");
                List<FileInfoDO> existList = fileInfoIService.list(queryWrapper);
                if (existList != null && !existList.isEmpty()) {
                    log.info("文件：{}，已存在", fileFullName);
                    continue;
                }
                FileInfoDO fileInfoDO = new FileInfoDO();
                fileInfoDO.setFileNo("FILE" + IdUtil.getSnowflakeNextIdStr());
                fileInfoDO.setOsType("win");
                fileInfoDO.setFirstCategory(firstCategory);
                fileInfoDO.setSecondCategory(secondCategory);
                fileInfoDO.setFileDir(fileDir);
                fileInfoDO.setFileName(fileName);
                fileInfoDO.setFileType(fileType);
                FileUtil.move(file, new File(fileInfoDO.getFileDir() + "//" + fileFullName), false);
                fileInfoIService.save(fileInfoDO);
                log.info("文件：{}，已存入数据库", fileFullName);
            }
        }
    }

    // 删除到回收站
    public void delFileByDB() {
        String dirPath = fileDir + "\\fileDel";
        LambdaQueryWrapper<FileInfoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileInfoDO::getIsDel, "1");
        List<FileInfoDO> list = fileInfoIService.list(queryWrapper);
        list.forEach(fileInfoDO -> {
            String fileFullName = fileInfoDO.getFileName() + "." + fileInfoDO.getFileType();
            FileUtil.move(new File(fileInfoDO.getFileDir() + "//" + fileFullName), new File(dirPath + "//" + fileFullName), true);
            log.info("文件：{}，移动到回收站", fileFullName);
        });
    }

    public Pair<String,String> getNameAndType(File file) {
        String fileFullName = file.getName();
        String fileName = null;
        String fileType = null;
        if (fileFullName.lastIndexOf(".") != -1) {
            fileName = fileFullName.substring(0, fileFullName.lastIndexOf("."));
            fileType = fileFullName.substring(fileFullName.lastIndexOf(".") + 1);
        } else {
            fileName = fileFullName;
        }
        return Pair.of(fileName, fileType);
    }

}
